package com.fingard.dsp.bank.directbank.chinaums01;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingleBat;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingleBat;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingleBat;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;

public class ChinaUMS01SinglePay extends ChinaUMS01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);

        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        if ("190806".equals(p_req1908.reqHeader.commandCode)) {
            tmpRetDetail = d_190806(p_req1908);
        } else {
            tmpRetDetail = d_190802(p_req1908);
        }

        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    private RetAtsSglDetail d_190802(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.payAct, "");
            if (actItem != null) {
                HashMap<String, String> mapParams = new HashMap<String, String>();

                mapParams.put("tranId", p_req1908.singleDetail.askNumber);
                mapParams.put("tranTime", Format.DateTime14Format.format(Format.DateTimeFormat.parse(p_req1908.reqHeader.transTime)));
                mapParams.put("currency", convertCurToBank(p_req1908.singleDetail.recCur));
                mapParams.put("rcvAcctNo", p_req1908.singleDetail.recAct);
                mapParams.put("rcvAcctName", p_req1908.singleDetail.recName);
                mapParams.put("rcvBankCode", "00000000");
                mapParams.put("rcvBankName", p_req1908.singleDetail.recBankName);
                mapParams.put("rcvBankSettleNo", "");
                mapParams.put("rcvBankSwitchNo", "");
                mapParams.put("tranAmt", StringHelper.amountMultiply100(p_req1908.singleDetail.payAmount));
                mapParams.put("certType", convertCertTypeToBank(p_req1908.singleDetail.certType));
                mapParams.put("certNo", p_req1908.singleDetail.certNum);
                mapParams.put("chkFlag", "0");
                mapParams.put("busiType", getBankConfig().getMapValueByKey("businessType_" + p_req1908.reqHeader.transType, "0"));
                mapParams.put("busiNo", "");
                String tranChannel = "";
                if ("1".equals(p_req1908.singleDetail.isPrivate)) {
                    tranChannel = "01"; /* 对私 */
                } else {
                    tranChannel = "22"; /* 对公 */
                }
                mapParams.put("tranChannel", tranChannel);

                String remark = p_req1908.singleDetail.memo;
                if (StringHelper.isNullOrEmpty(remark)) {
                    remark = p_req1908.singleDetail.purpose;
                }
                if (StringHelper.isNullOrEmpty(remark)) {
                    remark = p_req1908.singleDetail.abstractATS;
                }
                mapParams.put("remark", remark);
                mapParams.put("amtType", "00");
                mapParams.put("sndAcctNo", p_req1908.singleDetail.payAct);
                mapParams.put("sndAcctName", p_req1908.singleDetail.payName);
                mapParams.put("comName", "");
                mapParams.put("comCertNo", "");
                mapParams.put("resv1", p_req1908.singleDetail.askNumber);
                mapParams.put("resv2", p_req1908.singleDetail.askNumber);
                mapParams.put("resv3", p_req1908.singleDetail.askNumber);

                String urlSubmit = bankFront.getUrl("singlePaySubmit");
                WriteBankLogLn2("上海银联单笔实时代付交易服务地址: " + urlSubmit);

                String tmpStrRet = sendToBank(mapParams, urlSubmit, actItem);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    WriteBankLogLn2("银行响应数据明文:\r\n" + tmpStrRet);

                    Map<String, String> tmpRetMap = convertToMap(tmpStrRet);

                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.reqSeqID = tmpRetMap.get("tranId");
                    tmpRetDetail.respInfo = tmpRetMap.get("respMsg");
                    tmpRetDetail.transState = tmpRetMap.get("respCode");
                    tmpRetDetail.payInfoCode = tmpRetMap.get("respCode");

                    if (StringHelper.hasAnyChar(tmpRetMap.get("tranAmt"))) {
                        tmpRetDetail.transAmt = StringHelper.amountDivide100(tmpRetMap.get("tranAmt"));
                    } else {
                        tmpRetDetail.transAmt = p_req1908.singleDetail.payAmount;
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "银行响应数据为空";
                }
            } else {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "未找到账号[" + p_req1908.singleDetail.payAct + "]商户配置信息";
                tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return tmpRetDetail;
    }
    
    private RetAtsSglDetail d_190806(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.payAct, "unifiedorder");
            if (actItem == null) {
            	tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "未找到账号[" + p_req1908.singleDetail.payAct + "]商户配置信息";
                tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                tmpRetDetail.transState = PaymentState.FAIL;
                tmpRetDetail.payInfoCode = FailCode.E9981;
                return tmpRetDetail;
            }
            
            HashMap<String, String> mapParams = new HashMap<String, String>();

            mapParams.put("msgId", ""); /* 消息ID */
			mapParams.put("msgSrc", getMsgSrc()); /* 消息来源 */
			mapParams.put("msgType", "bills.refund"); /* 消息类型 */
			mapParams.put("requestTimestamp", Format.DateTimeFormat.format(new Date())); /* 报文请求时间 (格式:yyyy-MM-dd HH:mm:ss)*/
			mapParams.put("srcReserve", ""); /* 请求系统预留字段 */
			mapParams.put("billDate", Format.Date10Format.format(p_req1908.singleDetail.getPayDateTime())); /* 账单日期 (格式yyyy-MM-dd) */
			mapParams.put("billNo", p_req1908.singleDetail.recAct); /* 商户账单号 */
			mapParams.put("instMid", "QRPAYDEFAULT"); /* 业务类型 */
			mapParams.put("mid", actItem.merchantId); /* 商户号 */
			mapParams.put("tid", getTerminalNum()); /* 终端号 */
			mapParams.put("refundAmount", StringHelper.amountMultiply100(p_req1908.singleDetail.payAmount)); /* 要退货的金额 */
			String desc = p_req1908.singleDetail.useType;
			if (StringHelper.isNullOrEmpty(desc)) {
				desc = p_req1908.singleDetail.memo;
			}
			if (StringHelper.isNullOrEmpty(desc)) {
				desc = p_req1908.singleDetail.description;
			}
			mapParams.put("refundDesc", desc); /* 退货说明 */
			mapParams.put("signType", "MD5"); /* 签名算法 */
			
			String tmpStrRet = sendUnifiedOrder(mapParams, actItem);
            
            if (StringHelper.hasAnyChar(tmpStrRet)) {
                if (tmpStrRet.contains("{")) {
                	JSONObject tmpJsonResp = JSON.parseObject(tmpStrRet);
                	
                	tmpRetDetail.respCode = "0";
                	tmpRetDetail.respInfo = tmpJsonResp.getString("errMsg");
        			
        			String errCode = tmpJsonResp.getString("errCode");
        			String status = tmpJsonResp.getString("billStatus");
        			tmpRetDetail.transState = StringHelper.joinNotEmpty("+", errCode, status);
        			tmpRetDetail.payInfoCode = errCode;
                } else {
                	tmpRetDetail.respCode = "-1";
                	tmpRetDetail.respInfo = "银联响应数据格式非法";
                }
            } else {
            	tmpRetDetail.respCode = "-1";
            	tmpRetDetail.respInfo = "银联响应为空";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        if (StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID) && "-1".equals(tmpRetDetail.respCode)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        return tmpRetDetail;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1944.payAct, "");
            if (actItem != null) {
                HashMap<String, String> mapParams = new HashMap<String, String>();

                mapParams.put("tranId", p_req1944.askNumber);
                mapParams.put("tranTime", Format.DateTime14Format.format(p_req1944.getBgnDateTime()));
                mapParams.put("sysTranId", "");
                mapParams.put("origSysTranId", "");
                mapParams.put("origTranId", p_req1944.askNumber);
                mapParams.put("origTranDate", Format.Date8Format.format(p_req1944.getBgnDateTime()));
                mapParams.put("itemIndex", "");

                String urlSubmit = bankFront.getUrl("singlePayQuery");
                WriteBankLogLn2("上海银联单笔实时代付状态查询服务地址: " + urlSubmit);

                String tmpStrRet = sendToBank(mapParams, urlSubmit, actItem);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    WriteBankLogLn2("银行响应数据明文:\r\n" + tmpStrRet);

                    Map<String, String> tmpRetMap = convertToMap(tmpStrRet);

                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpRetMap.get("respMsg");
                    tmpRetDetail.reqSeqID = tmpRetMap.get("tranId");

                    String tmpRespCode = tmpRetMap.get("respCode");
                    if ("0000".equals(tmpRespCode)) {
                        tmpRetDetail.respInfo = tmpRetMap.get("origRespMsg");
                        tmpRetDetail.transState = StringHelper.joinNotEmpty("+", tmpRetMap.get("respCode"), tmpRetMap.get("origRespCode"));
                        tmpRetDetail.payInfoCode = tmpRetMap.get("origRespCode");
                    } else {
                        tmpRetDetail.transState = tmpRetMap.get("respCode");
                        tmpRetDetail.payInfoCode = tmpRetMap.get("respCode");
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "银行响应数据为空";
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未找到账号[" + p_req1944.payAct + "]商户配置信息";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1944.askNumber;
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
